package org.jsola.contract.task;

import lombok.extern.slf4j.Slf4j;
import org.jsola.common.DateKit;
import org.jsola.common.DateKit8;
import org.jsola.contract.constant.ContractConstants;
import org.jsola.contract.entity.CategoryDO;
import org.jsola.contract.entity.ContractDO;
import org.jsola.contract.entity.PartySignDO;
import org.jsola.contract.service.ICategoryService;
import org.jsola.contract.service.IContractService;
import org.jsola.contract.service.IContractSignCallbackService;
import org.jsola.contract.service.IPartySignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author JanusMix
 */
@Slf4j
@Component
public class ContractTaskService {

    @Autowired
    private IContractService contractService;
    @Autowired
    private ICategoryService categoryService;
    @Autowired
    private IPartySignService partySignService;
    @Autowired
    private List<IContractSignCallbackService> contractSignCallbackServiceList;

    /**
     * 修改到期合同的状态，10分钟一次
     */
    @Scheduled(cron = "0 0/10 * * * ?")
    public void updateContractExpireDays() {
        log.info("schedule task start:----------------------->修改到期合同的状态");
        //获取所有状态为待员工签署的合同
        List<ContractDO> contractList = contractService.selectAllReadySignContract();
        if (CollectionUtils.isEmpty(contractList)) {
            return;
        }
        //获取合同的所有分类
        List<Long> categoryIdList = contractList.parallelStream().map(ContractDO::getCategoryId).distinct().collect(Collectors.toList());
        List<CategoryDO> categoryList = categoryService.selectByIds(categoryIdList);
        if (CollectionUtils.isEmpty(categoryList)) {
            return;
        }
        // 合同有效天数为空的跳过
        Map<Long, Integer> categoryExpireDaysMap = categoryList.parallelStream().filter(categoryDO
                -> categoryDO.getExpireDays() != null).collect(Collectors.toMap(CategoryDO::getId, CategoryDO::getExpireDays));
        Date now = new Date();
        // 需要更改状态的合同
        List<ContractDO> updateContractList = new ArrayList<>();
        for (ContractDO contractDO : contractList) {
            Integer expireDays = categoryExpireDaysMap.get(contractDO.getCategoryId());
            if (expireDays == null) {
                continue;
            }
            if (ContractConstants.EXTERNAL_EXPIRE_DAYS.equals(expireDays)) {
                continue;
            }
            Date signDate = contractDO.getSignDate();
            if (signDate == null) {
                continue;
            }
            if (DateKit8.addDays(signDate, expireDays).getTime() > now.getTime()) {
                continue;
            }
            //修改合同状态
            log.info(contractDO.getName() + "已过期，id:" + contractDO.getId() + "，发起日期:" + DateKit.getDateTimeStr(signDate));
            ContractDO tempContract = new ContractDO();
            tempContract.setId(contractDO.getId());
            tempContract.setStatus(ContractConstants.CONTRACT_STATUS_FAILED);
            contractService.updateByIdSelective(tempContract, contractDO.getSiteId(), contractDO.getModifiedUserId());
            //修改签署方状态
            List<PartySignDO> partySignList = partySignService.selectByContractId(contractDO.getId(), contractDO.getSiteId());
            if (!CollectionUtils.isEmpty(partySignList)) {
                for (PartySignDO partySignDO : partySignList) {
                    PartySignDO tempPartySign = new PartySignDO();
                    tempPartySign.setId(partySignDO.getId());
                    tempPartySign.setStatus(ContractConstants.SIGN_STATUS_DELAYED);
                    partySignService.updateByIdSelective(tempPartySign, partySignDO.getSiteId(), partySignDO.getModifiedUserId());
                }
            }
            updateContractList.add(contractDO);
        }
        // 合同已过期回调函数
        for (IContractSignCallbackService contractSignCallbackService : contractSignCallbackServiceList) {
            contractSignCallbackService.onExpired(updateContractList);
        }
        log.info("schedule task end:----------------------->修改到期合同的状态");
    }

}
